<template>
  <div>
    <input
      type="text"
      placeholder="请输入用户名"
      v-model="username"
      @keyup.enter="handleEnterBtnClick"
    />
    <button @click="handleEnterBtnClick">进入聊天室</button>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'Login',
  setup() {
    const username = ref('');
    const router = useRouter();
    // 如果已登入，则直接进入聊天室
    onMounted(() => {
      username.value = localStorage.getItem('username');
      if (username.value) {
        router.push('/');
      }
    });
    // 进入聊天室
    const handleEnterBtnClick = () => {
      const tempUsername = username.value.trim();
      // 检查合法用户名
      if (tempUsername.length < 2) {
        alert('用户名不小于2位');
        return;
      }
      localStorage.setItem('username', tempUsername);
      username.value = '';
      router.push('/');
    };
    return {
      username,
      handleEnterBtnClick,
    };
  },
};
</script>

<style>
</style>
